import { Footer } from '@/components';
import { useTheme } from '@/hooks/useTheme';
import service from '@/services';
import { history } from '@@/core/history';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {
  message,
  Tabs,
  //message,
  theme,
} from 'antd';
import { useState } from 'react';
import styles from './index.less';

type LoginType = 'account' | 'phone';
const Page = () => {
  const [loginType, setLoginType] = useState<LoginType>('account');
  const { token } = theme.useToken();
  const themes = useTheme();
  const [loading, setLoading] = useState(false);

  const handleLogin = async (values: any) => {
    try {
      setLoading(true);
      // 登录
      const msg = await service.login.login({ ...values, type: 'account' });
      setLoading(false);
      if (msg.code === 200) {
        message.success(msg.message);
        localStorage.setItem('token', msg.data.token);
        // 如果 admin 是对象，转换为 JSON 字符串存储
        if (typeof msg.data.admin === 'object' && msg.data.admin !== null) {
          localStorage.setItem('admin', JSON.stringify(msg.data.admin));
        } else {
          localStorage.setItem('admin', String(msg.data.admin));
        }
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      } else {
        message.error('密码错误');
      }
    } catch (error) {
      if (error && typeof error === 'object' && 'response' in error) {
        const apiError = error as any;
        message.error(apiError.response?.data?.message || '登录失败');
      } else {
        message.error('登录失败');
      }
      setLoading(false);
    }
  };

  return (
    <div
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        backgroundImageUrl={themes.loginBg}
        logo={themes.logo}
        backgroundVideoUrl=""
        title={themes.title}
        containerStyle={{}}
        onFinish={handleLogin}
        loading={loading}
        // 添加配置来减少警告
        suppressHydrationWarning={true}
        actions={
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              flexDirection: 'column',
            }}
          ></div>
        }
      >
        <div style={{ marginTop: 12 }} />
        <Tabs
          centered
          activeKey={loginType}
          onChange={(activeKey) => setLoginType(activeKey as LoginType)}
        >
          <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
        </Tabs>
        <div />
        <div style={{ marginTop: 12 }} />
        {loginType === 'account' && (
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: (
                  <UserOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'请输入用户名'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'请输入密码'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>
        )}
        <div />
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
        </div>
      </LoginFormPage>
      <div className={styles.footerWrap}>
        <Footer />
      </div>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider>
      <Page />
    </ProConfigProvider>
  );
};
